<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>imosPlayerDemo</title>
    <script type="text/javascript" src="./common/axios.min.js"></script>
    <script type="text/javascript" src="./common/forge.min.js"></script>
    <script type="text/javascript" src="./common/jquery-1.9.1.js"></script>
</head>
<style>
    #all_function {
        display: none;
    }

    .test_title_icon {
        height: 24px;
        width: 24px;
        background-color: red;
    }

    #overlay {
        position: fixed;
        z-index: 100;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        font-size: 16px;
        background-color: rgba(0, 0, 0, 0.8);
    }

    .popup {
        background-color: #ffffff;
        position: relative;
        height: 240px;
        width: 400px;
        border: 5px;
        margin-top: 120px;
        margin-left: 90px;
        text-align: center;
    }

    .popup_title {
        height: 60px;
        line-height: 60px;
        border-bottom: solid 1px #cccccc;
    }

    .popup_content {
        height: 50px;
        line-height: 50px;
    }

    .popup_content_over {
        position: absolute;
        display: none;
        width: 200px;
        height: 100px;
        bottom: -60px;
        background: yellow;
    }
</style>

<body>
    <div style="">
        <div id="innerBox" style="width: 600px; height: 400px; background-color: black;"></div>
        <!-- <button onclick="playLive()">播放实况</button>
        <button onclick="stopPlay()" style="margin:4px 0">停止播放</button> -->
    </div>

    <div id='root' style="display: none;">
        umsip:<input placeholder="UMS服务器网络地址" type="text" value="" id="ip" />
        name:<input placeholder="UMS账户名" type="text" value="" id="name" />
        passwd:<input placeholder="UMS账户密码" type="text" value="" id="passwd" />
        <!-- 所有vdapi接口及imosSdk.min.js/imosPlayer.min.js一律往此端口请求 -->
        静态资源端口:<input placeholder="播放器SDK所在端口" type="text" value="7010" id="linkPort" />
        <!-- 所有VIID接口一律往此端口请求 -->
        VIID端口:<input placeholder="VIID所在端口" type="text" value="80" id="VIIDPort" />
        <button onclick="login()">1 登录</button>
        <button onclick="createWindow()">2 创建窗格</button>
        <div id="all_function" style="margin-top: 10px;">
            <button onclick="openLocalPlayer()">打开本地播放器</button>
            <button id='imos_check_open_btn' onclick="checkLocalPlayer()">检测本地播放器是否打开</button>
            <button onclick="checkInit()">检查是否初始化成功</button>
            <button onclick="registerLive()">注册生命周期回调</button>
            <div style="display: flex;margin-top: 10px;">
                <div id="innerBox" style="width: 600px; height:400px; background-color: black;">
                </div>
                <div style="border: 1px solid;width:400px;margin-left: 10px;padding: 4px;overflow: auto;">
                    【实况】
                    <p>
                        资源编码：<input id="liveResCode" class="resCode" type="text" value="574763701656093528-0-1" />
                        <button onclick="playLive()">播放实况</button>
                        <button onclick="playSwitch()" style="margin:4px 0">播放轮切</button>
                        <button onclick="stopPlay()" style="margin:4px 0">停止播放</button>
                        <button onclick="startToggle()" style="margin:4px 0">无黑屏切换相机</button>
                    </p>
                    <p>
                        <button onclick="playcatch()">抓拍</button>
                        <button onclick="onContinueSnap()">连续抓拍</button>
                    </p>
                    【广播对讲】
                    <br>
                    <input type="text" value="" id="broadcast_camera" placeholder="相机编码" />
                    <button onclick="startBroadcast()" style="margin:4px 0">启动当前相机广播</button>
                    <button onclick="stopBroadcast()" style="margin:4px 0">停止当前相机广播</button>
                    <button onclick="searchBroadcastStatus()">查询广播</button>
                    <br>
                    <br>
                    对讲成功后：
                    <br>
                    <input type="text" value="" id="MicVolume" placeholder="麦克风音量大小0-100" />
                    <button onclick="setMicVolume()">设置麦克风音量</button>
                    <button onclick="getMicVolume()">获取麦克风音量</button>
                </div>

                <div style="border: 1px solid;width: 270px;margin-left: 8px;padding: 4px;overflow: auto;">
                    【悬浮组件调试】
                    <p>
                        <button onclick="showDiv()">视频上层挖空</button>
                    </p>
                    <p>
                        <button onclick="setFloatForceVisible(false)">强制窗体进行隐藏</button>
                        <button onclick="setFloatForceVisible(true)">恢复</button>
                    </p>

                    <div id="overlay" style="display: none;">
                        <!-- 挖空区域 start -->
                        <div class="popup hollowDivClass">
                            <p class="popup_title">提示</p>
                            <p class="popup_content">挖空测试</p>
                            <div class="popup_content_over">新增节点溢出测试</div>
                            <div calss="popup_btn">
                                <button onclick="subTest()">新增节点溢出测试</button>
                                <button onclick="hideDiv()">关闭</button>
                            </div>
                        </div>
                        <!-- 挖空区域 end -->
                    </div>

                    【本地网络配置】
                    <br>
                    <p id="liveLink">
                        实况:
                        <input name="cl" type="radio" value="auto" onclick="liveNetLinkMode(this.value)">自适应</input>
                        <input name="cl" type="radio" value="tcp" onclick="liveNetLinkMode(this.value)"
                            checked>TCP</input>
                        <input type="checkbox" id="liveProxy" onclick="liveProxy()" checked>是否过MS</input>
                    </p>
                    <p id="replayLink">
                        回放:
                        <input name="fs" type="radio" value="udp" onclick="replayNetLinkMode(this.value)">UDP</input>
                        <input name="fs" type="radio" value="tcp" onclick="replayNetLinkMode(this.value)"
                            checked>TCP</input>
                        <input type="checkbox" id="replayProxy" onclick="replayProxy()" checked>是否过MS</input>
                    </p>
                    <p id="pictureFluency">
                        模式:
                        <input name="fluency" type="radio" value="0" onclick="setPictureFluency(this.value)"
                            checked>实时性优先</input>
                        <input name="fluency" type="radio" value="1"
                            onclick="setPictureFluency(this.value)">流畅性优先</input>
                        <input name="fluency" type="radio" value="2" onclick="setPictureFluency(this.value)">自适应</input>
                    </p>
                    <p>
                        启用抗丢包：
                        <input type="checkbox" id="resistLost"></input>
                    </p>
                    <p>
                        启用乱序整理：
                        <input type="checkbox" id="adjustPktSeq"></input>
                    </p>
                    <p>
                        <button onclick="confirmNetSetting()">确定</button>
                    </p>
                </div>
            </div>
            <div style="display: flex;">
                <div style="border: 1px solid;display: flex;">
                    <div style="border: 1px;width: 460px;margin: 10px 2px;padding: 5px;">
                        【录像检索条件】
                        <br>
                        <p id="rindistincQuery">
                            <input name="1" value="2" type="radio" onclick="findistincQuery(this.value)">前端录像</input>
                            <input name="1" value="1" type="radio" onclick="findistincQuery(this.value)"
                                checked>中心录像</input>
                            <input name="1" value="3" type="radio" onclick="findistincQuery(this.value)">模糊查询</input>
                        </p>
                        <p id="rdomainLevel">
                            <input name="2" value="0" type="radio" onclick="fdomainLevel(this.value)">检索注册域</input>
                            <input name="2" value="1" type="radio" onclick="fdomainLevel(this.value)"
                                checked>检索当前域</input>
                            <input name="2" value="2" type="radio" onclick="fdomainLevel(this.value)">云检索</input>
                        </p>
                        <p>
                            开始时间：
                            <input type="date" value="2022-02-10" id="startd" style="margin:4px 0" />
                            <input type="time" value="00:00:01" id="startt" style="margin:4px 0" />
                            <br />
                            <!-- 跳转时间：
                            <input type="date" value="" id="jumpTimeDate" />
                            <input type="time" value="" id="jumpTimeTime" />
                            <br /> -->
                            结束时间：
                            <input type="date" value="2022-02-10" id="endd" style="margin:4px 0" />
                            <input type="time" value="23:59:59" id="endt" style="margin:4px 0" />
                        </p>
                        资源编码：<input id="replayCode" class="resCode" type="text" value="" />
                    </div>
                    <div style="border: 1px;width: 420px;margin: 10px 2px;padding: 5px;">
                        【播放录像】
                        <p>
                            <!-- 回放倍速：<input id="speed" type="text" value="1" /> -->
                            <button onclick="startReplay()">播放回放</button>
                            <button onclick="searchRecord()">检索录像段</button>
                            <button onclick="switchPlay()">切换播放暂停状态</button>
                            <button id="switchSpeed" onclick="playSpeed()">切换到2倍速</button>
                            <button onclick="addCallback()">注册进度回调</button>
                            <br />
                            <button onclick="playLocalFile()">选择本地文件播放</button>
                        </p>
                        【录像下载】
                        <p>
                            录像类型：
                            <input name="downloadType" type="radio" value=3 onclick="setDownloadType(3)">MP4</input>
                            <input name="downloadType" type="radio" value=0 checked
                                onclick="setDownloadType(0)">TS</input>
                        </p>

                        <p id="downloadSpeed">
                            下载倍速：
                            <input name="dSpeed" value="1" type="radio" onclick="downloadSpeed(this.value)">1倍速</input>
                            <input name="dSpeed" value="2" type="radio" onclick="downloadSpeed(this.value)">2倍速</input>
                            <input name="dSpeed" value="4" type="radio" onclick="downloadSpeed(this.value)"
                                checked>4倍速</input>
                            <input name="dSpeed" value="8" type="radio" onclick="downloadSpeed(this.value)">8倍速</input>
                        </p>
                        <button onclick="startDownload()" id="downloadBtn">开始下载</button>
                        <button onclick="getAllTask()">获取所有下载任务</button>
                        <br>
                        <input type="text" value="" id="taskid" placeholder="任务id" />
                        <button onclick="cancelDownload()">取消下载</button>
                        <button onclick="getDownloadItemInfo()">获取任务状态</button>
                    </div>
                </div>
                <div style="border: 1px solid;width: 500x;padding: 5px;">
                    【其他工具】
                    <br><br>
                    工具栏控制:
                    <br>
                    <input name="4" value="1" type="radio" onclick="hideBtn(this.value)">隐藏全部</input>
                    <input name="4" value="4" type="radio" onclick="hideBtn(this.value)">隐藏回放进度条</input>
                    <input name="4" value="2" type="radio" onclick="hideBtn(this.value)">隐藏标题栏</input>
                    <input name="4" value="3" type="radio" onclick="hideBtn(this.value)">隐藏底部栏</input>
                    <button onclick="onHideBtn()">确定</button>
                    <button onclick="restore()">恢复所有隐藏</button>
                    <p>
                        <button onclick="setExTitle()">标题栏插入文本</button>
                        <br />
                        <button onclick="addToolBtn()">增加底部栏按钮</button>
                        <button onclick="searchBottomBtn()" style="margin:4px 0">所有底部栏图标ID</button>
                        <input id="bottomButtonID" placeholder="图标id" />
                        <button onclick="deleteBottomIcon()">确认删除</button>
                        <br />
                        <button onclick="playStatus()" style="margin:4px 0">获取播放状态</button>
                        <button onclick="getFuncInfo()" style="margin:4px 0">获取工具栏默认功能的状态</button>
                    </p>
                </div>
            </div>
            <br />
            <div class="forVideo"></div>
        </div>
    </div>
    <script>
        let _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';

        const passwordVal = 'yushi@123';
        const usernameVal = 'admin';
        let ipaddrVal = '111.120.11.161';
        let linkPortVal = 7010;
        let VIIDPortVal = 4311;
        let ezopenValue = '';
        let snCode = getUrlParam('snCode');
        let widthVal = getUrlParam('width');
        let heightVal = getUrlParam('height');
        let rectXVal = getUrlParam('rectX');
        let rectYVal = getUrlParam('rectY');

        // 解析 URL 参数的工具函数
        function getUrlParam(key) {
            const search = window.location.search.slice(1); // 去除问号 "?"
            const params = new URLSearchParams(search);
            return params.get(key); // 返回指定参数的值
        }

        console.log('widthVal: ', widthVal, 'heightVal: ', heightVal, 'rectXVal: ', rectXVal, 'rectYVal: ', rectYVal, );

        // 获取 div 元素并设置样式
        const divBox = document.getElementById('innerBox');
        if (divBox) {
            divBox.style.width = widthVal;   // 设置宽度
            divBox.style.height = heightVal; // 设置高度
        }

        // 获取 snCode
        console.log('从父页面接收的 snCode：', snCode); // 例如：123456

        async function getQueryParam(key) {
            try {
                var search = window.location.search.slice(1); // 去除问号 "?"
                var params = new URLSearchParams(search);
                snCode = params.get(key); // 返回指定参数的值
                console.log('123456789',snCode);

                const res = await axios({
                    method: "POST",
                    url: `http://111.120.11.161:4311/xapi/uap/v1/resource/transcode`,
                    headers: {
                        "Content-Type": "application/json; charset=utf8"
                    },
                    responseType: "json",
                    data: {
                        "resIDs":[ snCode ]
                    },
                });

                console.log(res);
                if(res.data.code === 0) {
                    return res.data.data.successList[0].resCode; // 直接返回结果
                }
                return ''; // 失败时返回空
            } catch (err) {
                console.log(err);
                return '';
            }
        }

        // 调用异步函数（需要在async环境中）
        (async () => {
            ezopenValue = await getQueryParam('snCode');
            // ezopenValue = '52058100001320000030';
            console.log('ezopenValue: ', ezopenValue);
            console.log('========== 登录 ==========');
            login();
        })();

        /** top层title */
        let topTitle = '安全管控智慧平台';/* undefined */
        /** iframe偏移量 */
        // let offset = [0, 0];
        let offset = [rectXVal, rectYVal];
        /** 国产PC计算坐标参数 */
        // let windowParams = undefined;
        /** 外层css缩放比例 */
        let sca = 1;

        /* offset = getDivPosition();
        // 计算div相对于页面左上角(0,0)的坐标
        function getDivPosition() {
            // const innerBoxDiv = document.getElementById('yushiHtmlId');
            const innerBoxDiv = document.getElementById('innerBox');

            // 获取元素相对于视口的位置
            const rect = innerBoxDiv.getBoundingClientRect();
            // 加上页面滚动的偏移量，得到绝对坐标
            // const x = ((rect.left + window.scrollX) * 63); // 相对于页面左侧的X坐标
            // const y = ((rect.top + window.scrollY) * 5.8);  // 相对于页面顶部的Y坐标
            return [ rect.x, rect.y ];
        } */
        // console.log('offset-offset-offset-offset-offset: ', offset);

        window.addEventListener('message', (e) => {
            console.log('message-message-message-message-message: ', e);
            if (e.data.type === "imosplayer") {
                topTitle = e.data.title;
                offset = [e.data.left, e.data.top];
                // windowParams = e.data.windowParams;
                sca = e.data.scale;
            }
        })

        //#region demo工具类
        class Base64 {
            static encode(input) {
                let output = '';
                let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
                let i = 0;

                input = Base64._utf8Encode(input);

                while (i < input.length) {
                    chr1 = input.charCodeAt(i++);
                    chr2 = input.charCodeAt(i++);
                    chr3 = input.charCodeAt(i++);

                    enc1 = chr1 >> 2;
                    enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
                    enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
                    enc4 = chr3 & 63;

                    if (isNaN(chr2)) {
                        enc3 = enc4 = 64;
                    } else if (isNaN(chr3)) {
                        enc4 = 64;
                    }

                    output =
                        output +
                        _keyStr.charAt(enc1) +
                        _keyStr.charAt(enc2) +
                        _keyStr.charAt(enc3) +
                        _keyStr.charAt(enc4);
                }

                return output;
            }

            static _utf8Encode(str) {
                str = str.replace(/\r\n/g, '\n');
                var utftext = '';

                for (var n = 0; n < str.length; n++) {
                    var c = str.charCodeAt(n);

                    if (c < 128) {
                        utftext += String.fromCharCode(c);
                    } else if (c > 127 && c < 2048) {
                        utftext += String.fromCharCode((c >> 6) | 192);
                        utftext += String.fromCharCode((c & 63) | 128);
                    } else {
                        utftext += String.fromCharCode((c >> 12) | 224);
                        utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                        utftext += String.fromCharCode((c & 63) | 128);
                    }
                }

                return utftext;
            }
        }
        /**
         * 随机码
         */
        getRandom = () => {
            function S4() {
                return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
            }
            return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
        };

        /**
         * 设置下载文件类型  mp4:3 ts:0
         */
        setDownloadType = (val) => {
            window._downloadType = val;
        }

        /**
         * 改下载倍速
         */
        downloadSpeed = (val) => {
            window._downloadSpeed = parseInt(val, 10)
        }

        /**
         * 是否显示回放按钮和进度条
         * @param {*} value
         */
        hideBtn = function (value) {
            window.__hideBtn = value;
        };

        //#endregion

        //#region 播放器初始化
        /**
         * 登录，初始化播放器
         */
        function login() {
            console.log('登录，初始化播放器');
            /* const password = document.getElementById('passwd').value;
            const username = document.getElementById('name').value;
            let ipaddr = document.getElementById('ip').value;
            let linkPort = document.getElementById('linkPort').value;
            let VIIDPort = document.getElementById('VIIDPort').value; */
            const password = passwordVal;
            const username = usernameVal;
            let ipaddr = ipaddrVal;
            let linkPort = linkPortVal;
            let VIIDPort = VIIDPortVal;

            let date = new Date();
            let day = ('0' + date.getDate()).slice(-2);
            let month = ('0' + (date.getMonth() + 1)).slice(-2);
            let today = date.getFullYear() + '-' + month + '-' + day;
            document.getElementById('endd').value = today;
            document.getElementById('startd').value = today;

            let liveNetProtocol = document.getElementById('liveLink').value;
            if (liveNetProtocol === undefined) {
                liveNetProtocol = 'tcp';
            }
            let replayNetProtocol = document.getElementById('replayLink').value;
            if (replayNetProtocol === undefined) {
                replayNetProtocol = 'tcp';
            }

            let liveByMS = document.getElementById('liveProxy').checked;
            let replayByMS = document.getElementById('replayProxy').checked;
            if (linkPort === '') {
                linkPort = '7010';
            }

            let nbsp = String.fromCharCode(160);
            let arr = [];
            arr.length = 40;
            let str = arr.fill(nbsp).join('');

            if (!ipaddr || !username || !password) {
                alert("ip、用户名、密码不能为空！");
                return;
            }
            const lang=(navigator.language || navigator.browserLanguage || 'en-us').replace('-','_').toLowerCase()

            axios({
                method: "POST",
                url: `http://${ipaddr}${VIIDPort && ":" + VIIDPort}/sw/login`,
                headers: {
                    "Content-Type": "application/json; charset=utf8"
                },
                responseType: "json"
            }).then((res) => {
                const AccessCode = res.data.AccessCode;//res.body改为res.data
                var md1 = forge.md.md5.create(); //md5
                var md2 = forge.md.md5.create(); //md5
                md1.update(password); //md5
                var passwordMd5 = md1.digest().toHex(); //md5
                let LoginSignature = Base64.encode(username) + AccessCode + passwordMd5;
                md2.update(LoginSignature); //md5
                LoginSignature = md2.digest().toHex(); //md5
                axios({
                    method: "POST",
                    url: `http://${ipaddr}${VIIDPort && ":" + VIIDPort}/sw/login`,
                    headers: {
                        "Content-Type": "application/json; charset=utf8"
                    },
                    responseType: "json",
                    data: {
                        UserName: username,
                        AccessCode,
                        LoginSignature,
                        isNewVersion:true,
                        other:true,
                        ip:ipaddr,
                        ClientIp:'',
                        // LoginExtInfo:{
                        //     IpAddress:"172.20.145.94"
                        // },
                        languageType:lang,
                    },

                }).then((res) => {
                    let script = document.createElement('script');
                    // ***必须动态引入播放器库文件，以免第三方运维成本上升***
                    // script.src = `http://${ipaddr}${linkPort && ":" + linkPort}/static/imosPlayer.min.js`

                    // **B3358P100H50以后可用以下url，方便第三方进行网络代理**
                    // script.src = `http://127.0.0.1:3004/imosPlayer.min.js`
                    script.src = `http://${ipaddr}${linkPort && ":" + linkPort}/vdapi/static/imosPlayer.min.js`

                    document.body.appendChild(script);
                    script.onload = function () {

                        // 悬浮方案要求网页title唯一，参照接口文档【悬浮播放器概念】
                        document.title = document.title + str + getRandom();

                        const token = res.data.AccessToken;
                        window.token = res.data.AccessToken;
                        keepalive(token);

                        // 本接口必须在init之前调用
                        console.log("setLinkPort", linkPort);
                        // window.imosPlayer.setLinkPort(linkPort);
                        window.imosPlayer.setLinkPort(4311);

                        console.log("init", ipaddr, token, topTitle || document.title, offset[0],offset[1]);
                        console.log("-----------------------------------------------------------------------", topTitle, document.title);
                        window.imosPlayer
                            .init({
                                ip: ipaddr,  // 必传
                                token: token,  // 必传
                                title: topTitle || document.title,  // 必传
                                offset:[Number(offset[0]),Number(offset[1])],
                                 // offset: [19,190]
                            })
                            .then((res) => {
                                if (res.ErrCode === 0) {
                                    console.log("cssScale", sca);
                                    window.imosPlayer.cssScale(sca);

                                    console.log("setLiveNetLinkMode", liveNetProtocol, liveByMS);
                                    window.imosPlayer.setLiveNetLinkMode(liveNetProtocol, liveByMS);
                                    console.log("setReplayNetLinkMode", replayNetProtocol, replayByMS);
                                    window.imosPlayer.setReplayNetLinkMode(replayNetProtocol, replayByMS);

                                    // 国产电脑坐标计算
                                    // window.imosPlayer.setWindowParams(windowParams);

                                    window.__login = true;

                                    window.imosPlayer.setLanguage(lang.split('_')[0])
                                    /* alert('登录成功请创建窗格（建议打开F12方便查看运行结果）'); */
                                    // setTimeout(() => {
                                        /* 创建窗格 */
                                        console.log('========== 创建窗格 ==========');
                                        createWindow();
                                    // }, 200);

                                } else {
                                    alert(res.ErrMsg);
                                }
                            })
                            .catch((err) => {
                                console.error(err);
                            });
                    };
                    script.onerror = (e) => {
                        console.error(e);
                    };
                }).catch(() => alert("登录失败！！！"));
            }).catch(() => alert("登录失败！！！"));
        };

        /**
         * 检查是否初始化成功
         */
        checkInit = () => {
            console.log("checkInit");
            let res = window.imosPlayer.checkInit();
            console.log("checkInit", res)
            alert(res ? "已初始化" : "未初始化")
        };

        /**
         * 账户保活
         */
        function keepalive(token) {
            /* let ipaddr = document.getElementById('ip').value;
            let linkPort = document.getElementById('linkPort').value;
            let VIIDPort = document.getElementById('VIIDPort').value; */

            let ipaddr = ipaddrVal;
            let linkPort = linkPortVal;
            let VIIDPort = VIIDPortVal;

            if (linkPort === '') {
                linkPort = '80';
            }

            axios({
                method: "POST",
                url: `http://${ipaddr}${VIIDPort && ":" + VIIDPort}/VIID/hadesadapter/user/keepalive`,
                headers: {
                    "Content-Type": "application/json; charset=utf8",
                    Authorization: token,
                },
                responseType: "json"
            }).then((res) => {
                    console.log("keepalive:",res);
                    let reConnect = 0;
                    let time = setInterval(() => {
                        axios({
                            method: "POST",
                            url: `http://${ipaddr}${VIIDPort && ":" + VIIDPort}/VIID/hadesadapter/user/keepalive`,
                            headers: {
                                "Content-Type": "application/json; charset=utf8",
                                Authorization: token,
                            },
                            responseType: "json"
                        }).then((res2) => {
                            if (res2.data.ErrCode !== 0) {
                                reConnect++;
                                if (reConnect > 5) {
                                    clearInterval(time);
                                    reConnect = 0;
                                    console.warn('user dead');
                                }
                            } else {
                                reConnect = 0;
                            }
                        })
                    }, 30000);
            })
        };

        /**
         * 创建窗格
         */
        createWindow = async () => {
            if (!window.__login) {
                alert("先登录");
                return;
            }
            if (window._iframeId) {
                alert("本demo仅演示创建一个窗格");
                return;
            };

            let all = document.getElementById("all_function");
            all.style.display = "block";

            console.log("createPanelWindow");
            let videoDom = await window.imosPlayer.createPanelWindow();
            // 窗格默认400*400，通过样式改宽高
            videoDom.style.width = widthVal;
            videoDom.style.height = heightVal;

            console.log("setVoidClassName");
            window.imosPlayer
                .setVoidClassName(videoDom, {
                    className: 'window_class',
                })
                .then((e) => {
                    console.log(e);
                });

            /* // 限制范围 */
            /* let array = document.getElementsByClassName('imosPlayer_class');
            console.log("setViewDomByClassName", array);
            window.imosPlayer.setViewDomByClassName({
                className: 'window_class',
                doms: [array[0]],
            }); */

            window._iframeId = videoDom.id;

            // 将窗格放入期望位置
            let divDom = document.getElementById('innerBox');
            divDom.style.width = widthVal;
            divDom.style.height = heightVal;
            divDom.appendChild(videoDom);

            // setTimeout(() => {
                /* 播放实况 */
                console.log('========== 播放实况 ==========');
                playLive();
            // }, 200);

        }


        /**
         * 打开本地播放器
         */
        openLocalPlayer = function () {
            const $iframe = document.createElement('iframe');
            $iframe.style.display = 'none';
            $iframe.src = 'imos://startXPWebPlayer';
            $iframe.onload = () => {
                // 5S之后清除
                const timer = setTimeout(() => {
                    clearTimeout(timer);
                    document.body.removeChild($iframe);
                }, 5000);
            };
            document.body.appendChild($iframe);
        };

        /**
         * 检测本地播放器是否打开
         */
        checkLocalPlayer = function () {
            let btn = window.document.getElementById('imos_check_open_btn');
            console.log("checkOutWebPlayer");
            window.imosPlayer.checkOutWebPlayer().then((res) => {
                if (res.ErrCode === 0) {
                    btn.innerText = '打开播放器成功';
                } else {
                    btn.innerText = res.ErrMsg;
                }
            });
        };

        //#endregion

        //#region 注册回调
        /**
         * 注册生命周期回调
         */
        function registerLive() {
            window.imosPlayer.registerLiveMsg((res) => console.log("registerLive", res));
        }

        //#endregion

        //#region 实况
        /**
         * 播放实况
         */
        playLive = function () {

            if (!window.token) {
                // alert('请先登录');
                return;
            }
            /* let resCode = document.getElementById('liveResCode').value; */
            let resCode = ezopenValue;

            console.log("播放实况 - resCode: ", resCode);
            window.imosPlayer
                .playLive(window._iframeId, {
                    camera: resCode,
                    title: resCode,
                    stream: 1,
                })
                .then((e) => {
                    console.log("playLive", e);
                });
        };

        /**
         * 轮切
         */
        playSwitch = () => {
            /* let switchRes = document.getElementById('liveResCode').value; */
            let switchRes = ezopenValue;
            window.imosPlayer
                .startSwitch(window._iframeId, {
                    switchRes: switchRes,
                    title: switchRes,
                })
                .then((e) => {
                    console.log(e);
                });
        };

        /**
         * 不黑屏切换实况
         */
        startToggle = () => {
            /* let toggleCode = document.getElementById('liveResCode').value; */
            let toggleCode = ezopenValue;
            window.imosPlayer.startToggle(window._iframeId, {
                camera: toggleCode,
                title: toggleCode,
            }).then((res)=>{
                console.log("startToggle", res);
            });
        };

        /**
         * 停止播放
         */
        stopPlay = function () {
            if (!window.token) {
                // alert('请先登录');
                return;
            }
            window.imosPlayer.playStop(window._iframeId).then((e) => {
                console.log("stopPlay", e);
            });
        };

        /**
         * 抓拍单张
         */
        playcatch = function () {
            window.imosPlayer
                .playCatch(window._iframeId, {
                    imageType: 'image/jpeg',
                })
                .then((e) => {
                    console.log("playCatch", e);
                    let arr1 = e.Img.split(',');
                    let mime = arr1[0].match(/:(.*?);/)[1];
                    let bstr = atob(arr1[1]),
                        n = bstr.length,
                        u8arr = new Uint8Array(n);
                    while (n--) {
                        u8arr[n] = bstr.charCodeAt(n);
                    }
                    let blob = new Blob([u8arr], {
                        type: mime,
                    });
                    saveAs(blob, 'test.jpg');
                });
        };

        /**
         * 开始/停止连续抓拍
         */
        onContinueSnap = function () {
            // 点一下开，再点一下停
            window.imosPlayer.onContinueSnap(window._iframeId).then((e) => {
                console.log("onContinueSnap", e);
                console.log("forceRefreshVoid");
                window.imosPlayer.forceRefreshVoid();
            });
        };
        //#endregion

        //#region 回放&下载
        /**
         * 播放回放
         */
        startReplay = function () {
            if (!window.token) {
                alert('请先登录');
                return;
            }

            let str = '';
            str = document.getElementById('startd').value + ' ' + document.getElementById('startt').value;

            let start = new Date(str);
            str = document.getElementById('endd').value + ' ' + document.getElementById('endt').value;
            let end = new Date(str);

            // 倍速
            // let jumpSpeed;
            // let speed = document.getElementById('speed').value;
            // if (speed !== '') {
            //     jumpSpeed = parseInt(speed, 10);
            // }
            // let jump = document.getElementById('jumpTimeDate').value + ' ' + document.getElementById('jumpTimeTime').value;

            // 播放从跳转点开始
            // let jumpTime;
            // if (jump !== ' ') {
            //     jumpTime = new Date(jump);
            // }

            let resCode = document.getElementById('replayCode').value;

            let indistincQuery = parseInt(document.getElementById('rindistincQuery').value, 10);
            if (isNaN(indistincQuery)) {
                indistincQuery = 1;
            }

            let domainLevel = parseInt(document.getElementById('rdomainLevel').value, 10);
            if (isNaN(domainLevel)) {
                domainLevel = 1;
            }

            window.imosPlayer
                .playRecord(window._iframeId, {
                    camera: resCode,
                    title: resCode,
                    start: start,
                    end: end,
                    searchType: {
                        indistincQuery: indistincQuery,
                        domainLevel: domainLevel,
                        type: 3,
                    },
                    // speed: jumpSpeed,
                    // jumpTime: jumpTime,
                })
                .then((e) => {
                    console.log("playRecord", e);
                });
        };

        /**
         * 添加回放进度回调
         */
        addCallback = function () {
            window.imosPlayer.setReplayProcessCb(window._iframeId, {
                callback: (e) => {
                    console.log('setReplayProcessCb', e);
                },
            });
        };

        /**
         * 设置播放速度
         */
        playSpeed = function () {
            let btn = document.getElementById('switchSpeed');
            let speed = 2;

            if (typeof btn.nextSpeed === 'number') {
                speed = btn.nextSpeed;
            }
            window.imosPlayer.recordSpeed(window._iframeId, { speed: speed }).then((e) => {
                console.log("recordSpeed", e);
            });
            switch (speed) {
                case 1:
                    btn.nextSpeed = 2;

                    btn.innerText = '切换到' + btn.nextSpeed + '倍速';
                    break;
                case 2:
                    btn.nextSpeed = 4;

                    btn.innerText = '切换到' + btn.nextSpeed + '倍速';
                    break;
                case 4:
                    btn.nextSpeed = 1;

                    btn.innerText = '切换到' + btn.nextSpeed + '倍速';
                    break;
                default:
                    break;
            }
        };

        /**
         * 检索录像
         */
        searchRecord = function () {
            let str = '';
            str = document.getElementById('startd').value + ' ' + document.getElementById('startt').value;


            let start = new Date(str);

            str = document.getElementById('endd').value + ' ' + document.getElementById('endt').value;

            let end = new Date(str);

            let resCode = document.getElementById('replayCode').value;

            let indistincQuery = parseInt(document.getElementById('rindistincQuery').value, 10);
            if (isNaN(indistincQuery)) {
                indistincQuery = 1;
            }

            let domainLevel = parseInt(document.getElementById('rdomainLevel').value, 10);
            if (isNaN(domainLevel)) {
                domainLevel = 1;
            }

            window.imosPlayer
                .searchRecord({
                    camera: resCode,
                    start: start,
                    end: end,
                    searchType: {
                        indistincQuery: indistincQuery,
                        domainLevel: domainLevel,
                        type: 3,
                    },
                })
                .then((e) => {
                    console.log("searchRecord", e);
                });
        };

        /**
         * 本地文件播放
         */
        playLocalFile = async function () {
            let ret = await window.imosPlayer.playLocalFile(window._iframeId, { title: undefined });
            console.log("playLocalFile", ret);
        };

        /**
         * url播放
         */
        playURL = async function () {
            let url = document.getElementById('net_file_' + window._iframeId).value;

            let ret = await window.imosPlayer.playURLFile(window._iframeId, {
                url: url,
                title: 'url播放'
            });
            console.log("playURLFile", ret);
        };

        /**
         * 播放器内部检测切换录像暂停/播放状态
         */
        switchPlay = function () {
            window.imosPlayer
                .switchPlayStatus(window._iframeId, { canPlay: undefined })
                .then((res) => {
                    console.log("switchPlayStatus", res);
                });
        };

        /**
         * 开始下载录像
         */
        startDownload = () => {
            let str = '';
            str =
                document.getElementById('startd').value +
                ' ' +
                document.getElementById('startt').value;
            let start = new Date(str);
            str = document.getElementById('endd').value + ' ' + document.getElementById('endt').value;
            let end = new Date(str);
            let resCode = document.getElementById('replayCode').value;
            // let scramble = document.getElementById('scramble').checked;
            let indistincQuery = parseInt(document.getElementById('rindistincQuery').value, 10);
            if (isNaN(indistincQuery)) {
                indistincQuery = 1;
            }

            let domainLevel = parseInt(document.getElementById('rdomainLevel').value, 10);
            if (isNaN(domainLevel)) {
                domainLevel = 1;
            }

            let speed = window._downloadSpeed;
            if (isNaN(speed)) {
                speed = 4;
            }
            console.log(speed);

            window.imosPlayer.downloadRecord({
                camera: resCode,
                start: start,
                end: end,
                searchType: {
                    indistincQuery: indistincQuery,
                    domainLevel: domainLevel,
                    type: 3,
                },
                filename: resCode + '的下载文件',
                speed: speed,
                ext: window._downloadType || 0,
                // scramble: scramble,
                cameraType: 2,
            }).then((res) => console.log("downloadRecord", res));
        };

        /**
         * 取消下载
         */
        cancelDownload = () => {
            let task = document.getElementById('taskid').value;
            window.imosPlayer.cancelDownload(task).then((res) => {
                console.log('canceldownload', res);
            });
        };

        /**
         * 获取所有下载任务ID
         */
        getAllTask = async () => {
            let tasks = await window.imosPlayer.getDownloadTasks();
            console.log('getDownloadTasks', tasks);
        };

        /**
         * 根绝任务ID查询下载状态
         */
        getDownloadItemInfo = () => {
            let task = document.getElementById('taskid').value;
            window.imosPlayer.getDownloadItemInfo(task).then((res) => {
                console.log('getDownloadItemInfo', res);
            });
        };
        //#endregion

        //#region 播放器公共
        /**
         * 添加一个图标
         */
        addToolBtn = function () {
            window.imosPlayer.addPanelBtn(window._iframeId, {
                button: {
                    id: 'button1',
                    className: 'test_title_icon', // 图标用样式改
                    tip: '测试按钮',
                },
                position: 'bottom',
                clickFunc: (el) => {
                    console.log("addPanelBtn", el);
                },
            });
        };

        /**
         * 删除底部图标
         */
        deleteBottomIcon = async function () {
            let id = document.getElementById("bottomButtonID").value;
            let res1 = await imosPlayer.searchBottomBtn(window._iframeId);
            if (Array.isArray(res1?.bottomButt) && res1.bottomButt.includes(id)) {
                // 先查按钮存不存在，存在则删除
                window.imosPlayer.delPanelBtn('window._iframeId', {
                    buttonID: id,
                    position: 'bottom'
                }).then((el) => {
                    console.log("delPanelBtn", el);
                });
            } else {
                console.log("not found" + id)
            }
        }

        /**
         * 搜索标题按钮
         */
        searchTitleBtn = function () {
            window.imosPlayer.searchTitleBtn(window._iframeId).then((el) => {
                console.log("searchTitleBtn", el);
            });
        };

        /**
         * 搜索底部工具栏按钮
         */
        searchBottomBtn = function () {
            window.imosPlayer.searchBottomBtn(window._iframeId).then((el) => {
                console.log("searchBottomBtn", el);
            });
        }

        /**
         * 插入标题文本
         */
        setExTitle = function () {
            window.imosPlayer.setExTitle(window._iframeId, { exTitle: "---我是插入的文本" })
                .then((res)=>console.log("setExTitle", res));
        };

        //绑定录像查询类型value
        findistincQuery = function (value) {
            document.getElementById('rindistincQuery').value = value;
        };

        fdomainLevel = function (value) {
            document.getElementById('rdomainLevel').value = value;
        };

        //设置网络连接方式
        liveNetLinkMode = function (value) {
            document.getElementById('liveLink').value = value;
        };

        liveProxy = function () {
            document.getElementById('liveProxy').checked;
        };

        replayNetLinkMode = function (value) {
            document.getElementById('replayLink').value = value;
        };

        replayProxy = function () {
            document.getElementById('replayProxy').checked;
        };

        setPictureFluency = function (value) {
            window._fluency = parseInt(value, 10);
        };

        confirmNetSetting = function () {
            let liveNetProtocol = document.getElementById('liveLink').value;
            if (liveNetProtocol === undefined) {
                liveNetProtocol = 'tcp';
            }
            let replayNetProtocol = document.getElementById('replayLink').value;
            if (replayNetProtocol === undefined) {
                replayNetProtocol = 'tcp';
            }

            let fluency = window._fluency;
            if (fluency === undefined) {
                fluency = 0;
            }

            let liveByMS = document.getElementById('liveProxy').checked;
            let replayByMS = document.getElementById('replayProxy').checked;
            let resistLost = document.getElementById('resistLost').checked;
            let adjustPktSeq = document.getElementById('adjustPktSeq').checked;
            window.imosPlayer.setLiveNetLinkMode(liveNetProtocol, liveByMS);
            console.log("setLiveNetLinkMode", liveNetProtocol, liveByMS);
            window.imosPlayer.setReplayNetLinkMode(replayNetProtocol, replayByMS);
            console.log("setReplayNetLinkMode", replayNetProtocol, replayByMS);
            window.imosPlayer.setPictureFluency(fluency);
            console.log("setPictureFluency", fluency);
            window.imosPlayer.setNetResistance(resistLost, adjustPktSeq);
            console.log("setNetResistance", resistLost, adjustPktSeq);
            window.imosPlayer.sendWebPlayerCfg();
            console.log("sendWebPlayerCfg");
        };


        /**
         * 获取播放状态
         */
        playStatus = function () {
            window.imosPlayer.playStatus(window._iframeId).then((e) => {
                console.log("playStatus", e);
            });
        };

        /**
         * 获取窗格自带功能的状态
         */
        getFuncInfo = function () {
            window.imosPlayer.getFuncInfo(window._iframeId).then((e) => {
                console.log("getFuncInfo", e);
            });
        };

        /**
         * 确定隐藏
         */
        onHideBtn = function () {
            let type = parseInt(window.__hideBtn, 10);
            window.imosPlayer.hiddenVideoBtn(window._iframeId, {
                type: type,
            }).then((res) => console.log("hiddenVideoBtn", res));
        };

        /**
         * 恢复全部隐藏
         */
        restore = function () {
            window.imosPlayer.setVideoProps(window._iframeId, {
                needControls: true,
                needReplayControls: true,
                enableTitle: true,
                enableLiveBottom: true
            }).then((res) => console.log("setVideoProps", res));
        };
        //#endregion

        //#region 悬浮调试
        /**
         * 悬浮控件强制窗体进行隐藏
         */
        setFloatForceVisible = function (visible) {
            window.imosPlayer.setFloatForceVisible({
                className: 'window_class',
                visible: visible,
            });
        };

        /**
         * 挖空测试
         */
        showDiv = () => {
            let overlay = document.getElementById('overlay');
            overlay.style.display = 'block';
            window.imosPlayer.setVoidBroadCastRegion({
                voidClassName: 'window_class',
                region: { class: 'hollowDivClass' },
            });
        }

        /**
         * 新增节点挖空更新
         */
        subTest = () => {
            let sub = document.getElementsByClassName('popup_content_over')[0];
            sub.style.display = "block";
            window.imosPlayer.setVoidBroadCastRegion({
                voidClassName: 'window_class',
                region: { class: ["hollowDivClass", "popup_content_over"] },
            });
        }

        /**
         * 结束挖空测试
         */
        hideDiv = () => {
            let overlay = document.getElementById('overlay');
            overlay.style.display = 'none';
            let sub = document.getElementsByClassName('popup_content_over')[0];
            sub.style.display = "none";
        };

        //#endregion

        //#region 广播
        /**
         * 启动广播
         */
        startBroadcast = function () {
            let camera = document.getElementById(`broadcast_camera`).value;
            let cameraArr = camera.split(',');
            let VocBrdUnit = [];
            cameraArr.forEach((ele) => {
                VocBrdUnit.push({
                    CameraCode: ele,
                });
            });
            window.imosPlayer.startVoiceBroadcast(VocBrdUnit).then((res) => {
                console.log("startVoiceBroadcast", res);
            });
        };
        /**
         * 停止广播
         */
        stopBroadcast = function () {
            let camera = document.getElementById(`broadcast_camera`).value;
            window.imosPlayer.stopVoiceBroadcast([{ CameraCode: camera }]).then((res) => {
                console.log("stopVoiceBroadcast", res);
            });
        };
        /**
         * 查询广播
         */
        searchBroadcastStatus = function () {
            window.imosPlayer.searchBroadcastStatus().then((res) => {
                console.log("searchBroadcastStatus", res);
            });
        };

        /**
         * 设置麦克风音量
         */
        setMicVolume = function () {
            let num = document.getElementById(`MicVolume`).value - 0;
            window.imosPlayer.setMicVolume(num);
            console.log("setMicVolume", "ok");
        };
        /**
         * 获取麦克风音量
         */
        getMicVolume = async function () {
            await window.imosPlayer.getMicVolume().then((e) => {
                console.log("getMicVolume", e);
            });
        };
        //#endregion
    </script>

</body>

</html>
